﻿using IT_RoadBlock.Comands;
using IT_RoadBlock.DataContexts;
using IT_RoadBlock.Dto;
using IT_RoadBlock.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IT_RoadBlock.ViewModes
{
    public class ProjectInjectionViewModel : ListRelayCommand<TProjectInjectionInfo>
    {
        public FyDbContext DbContext = new FyDbContext();
        private string projectCode = "";
        private string hashCode = "";


        /// <summary>
        /// 搜索添加
        /// </summary>
        public string HashCode
        {
            get => hashCode; set
            {
                hashCode = value;
                OnPropertyChanged(nameof(HashCode));
            }
        }

        public string ProjectCode
        {
            get => projectCode; set
            {
                projectCode = value;
                OnPropertyChanged(nameof(ProjectCode));
            }
        }

        public ProjectInjectionViewModel()
        {
            SearchCmdExecute(null);
        }

        public override void RemoveItemsCmdExecute(TProjectInjectionInfo obj)
        {
            if (this.DataList?.Any() == true)
            {
                IEnumerable<TProjectInjectionInfo> removeItems = this.DataList.Where(p => p._DataSelected);
                if (!removeItems.Any())
                {
                    DialogWindow?.Invoke(this, ResultFactory.Ok("请选择需要删除的数据!"));
                    return;
                }
                DbContext.InjectionDbSet.RemoveRange(removeItems);
                DbContext.SaveChanges();
                SearchCmdExecute(null);
            }
        }

        public override void SearchCmdExecute(TProjectInjectionInfo obj)
        {
            DbContext.Database.Log = Console.Write;
            IQueryable<TProjectInjectionInfo> queryables1 = DbContext.InjectionDbSet.Where(p => 1 == 1);
            if (!string.IsNullOrEmpty(this.HashCode))
            {
                queryables1 = queryables1.Where(p => p.HashCode.Contains(this.HashCode));
            }
            if (!string.IsNullOrEmpty(this.ProjectCode))
            {
                queryables1 = queryables1.Where(p => p.ProjectCode.Contains(this.ProjectCode));
            }
            int total = queryables1.Count();
            this.DataList = queryables1.OrderBy(p => p.CreateTime).Skip((this.PageNumber - 1) * this.PageSize).Take(this.PageSize).ToList();
            this.PageCount = total % this.PageSize == 0 ? total / this.PageSize : total / this.PageSize + 1;
        }

        ~ProjectInjectionViewModel()
        {
            DbContext?.Dispose();
        }
    }
}
